<template>
  <div class="t-table">
    <el-link
      class="t-f-r t-m-b-10"
      v-if="customFields"
      @click="showCustomFields = true"
      type="primary"
      :underline="false"
    >
      <i class="el-icon-s-operation"></i> 自定义字段</el-link
    >
    <el-table
      ref="tTable"
      size="small"
      border
      current-row-key="id"
      :data="dataInfo"
      @filter-change="handlerFilter"
      @sort-change="handlerSort"
      :lazy="lazy"
      :load="load"
      @row-click="rowClick"
      :tree-props="treeProps"
      :row-key="rowKey"
      @selection-change="handleSelectionChange"
      v-loading="loading"
      :highlight-current-row="true"
      :header-cell-style="tableHeaderStyle"
    >
      <el-table-column v-if="expand" type="expand">
        <template slot-scope="scope">
          <TableExtend
            :key="scope.$index"
            :row="scope.row"
            :render="expand"
            :index="scope.$index"
          ></TableExtend>
        </template>
      </el-table-column>
      <!-- 复选框 -->
      <el-table-column
        v-if="checkbox"
        :selectable="selectEnable"
        type="selection"
        width="55"
      ></el-table-column>
      <!-- 序号 -->
      <el-table-column
        v-if="number"
        label="序号"
        type="index"
        width="55"
        :index="indexMethod"
      >
      </el-table-column>

      <!-- 表格列  -->
      <template v-for="(item, key) in tableColumns" :data-id="key">
        <el-table-column
          :key="key"
          :ref="'col-' + item.prop"
          :width="item.width ? item.width : null"
          :prop="item.prop"
          :column-key="item.prop"
          :label="item.label"
          :show-overflow-tooltip="item.showOverflow"
          :sortable="item.sort ? 'custom' : false"
          :align="item.align ? item.align : align"
          :fixed="'fixed' in item && item.fixed"
          :filters="item.filter ? item.filter.data : null"
          :filter-multiple="
            item.filter
              ? item.filter.multiple === false
                ? item.filter.multiple
                : true
              : true
          "
        >
          <template slot-scope="scope">
            <template v-if="'render' in item">
              <TableExtend
                :key="scope.$index"
                :row="scope.row"
                :render="item.render"
                :index="scope.$index"
              ></TableExtend>
            </template>
            <template v-else>
              {{ scope.row[item.prop] }}
            </template>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <el-pagination
      v-if="page"
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="filterValue.limit"
      :current-page="filterValue.page"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
    <t-dialog title="自定义字段" width="50%" v-model="showCustomFields">
      <t-custom-fields
        ref="customFields"
        :columns="columns"
        :sortCols="sortCols"
        :fileds="fileds"
        @close="showCustomFields = false"
        @change="changeCustomFields"
        @success="setCustomFields"
      />
    </t-dialog>
  </div>
</template>

<script>
import Sortable from "sortablejs";
import request from "@/utils/axios";
import TableExtend from "@/mixins/tableExtend";
export default {
  props: {
    customFields: {
      type: Boolean,
      default: false,
    },
    method: {
      type: String,
      default: "get",
    },
    number: {
      type: Boolean,
      default: true,
    },
    url: String,
    columns: Array,
    page: {
      type: Boolean,
      default: true,
    },
    checkbox: {
      type: Boolean,
      default: false,
    },
    dataCustom: {
      type: String,
    },
    treeProps: {
      type: Object,
      default: () => {
        return { children: "children", hasChildren: "hasChildren" };
      },
    },
    childrenName: {
      type: String,
      default: "children_count",
    },
    hasChildrenName: {
      type: String,
      default: "hasChildren",
    },
    rowKey: {
      type: String,
      default: "ID",
    },
    lazy: {
      type: Boolean,
      default: false,
    },
    loadChilren: {
      type: Function,
    },
    expand: {
      type: [Function, Boolean, String, Number],
      default: false,
    },
    sortTable: {
      //是否开启表格拖动排序
      type: Boolean,
      default: false,
    },
    filterCustom: {
      type: Boolean,
      default: false,
    },
    extendFilterValue: {
      type: Object,
      default: () => {
        return {};
      },
    },
    defaultRquest: {
      type: Boolean,
      default: true,
    },
    align: {
      type: String,
      default: "left",
    },
    extendDataKey: {
      type: String,
      default: "",
    },
    selectTable: {
      type: Function,
      default: () => {
        return () => {};
      },
    },
    //设置table头颜色
    tableHeaderStyle: {
      type: Function,
      default: ({ row, column, rowIndex, columnIndex }) => {
        if (rowIndex === 0) {
          return `
            background-color: #f5f5fa;
            color: #333;
            font-size:14px;
            height: 48px;
            font-weight:bold;
          `;
        }
      },
    },
  },
  data() {
    return {
      showCustomFields: false,
      loading: false,
      dataInfo: [],
      filterValue: {
        page: 1,
        limit: 10,
      },
      total: 0,
      result: null,
      sort: {},
      tableColumns: [],
      sortCols: [],
      fileds: [],
    };
  },
  components: { TableExtend },
  mounted() {
    this.init();
    this.tableColumns = this.columns.filter((item) => {
      let res = false;
      if ("customField" in item && item.customField) {
        res = false;
      } else {
        res = true;
      }
      return res;
    });
  },
  methods: {
    changeCustomFields(d) {
      this.fileds = d;
    },
    //处理自定义字段回显
    setCustomFields(cols) {
      this.tableColumns = cols;
      let sortCols = [];
      this.tableColumns.forEach((_item) => {
        this.columns.forEach((item, index) => {
          if (item.label == _item.label) {
            sortCols.push(_item.label);
          }
        });
      });
      this.sortCols = sortCols;
    },
    selectEnable(row, rowIndex) {
      return this.selectTable(row, rowIndex);
    },
    init() {
      if (this.defaultRquest) {
        this.renderTable();
      }
      if (this.sortTable) {
        this.initSortable();
      }
    },
    //表格拖动排序
    initSortable() {
      const EL = document.querySelector(".el-table__body-wrapper tbody");
      var sortable = new Sortable(EL, {
        animation: 150,
        onEnd: (evt) => {
          let dataInfo = JSON.parse(JSON.stringify(this.dataInfo));
          const tempItem = dataInfo.splice(evt.oldIndex, 1)[0];
          dataInfo.splice(evt.newIndex, 0, tempItem);
          this.$emit("getSortTableData", dataInfo);
        },
      });
    },
    //懒加载下级
    load(tree, treeNode, resolve) {
      this.loadChilren(tree).then((res) => {
        resolve(res);
      });
    },
    // 表头筛选项
    handlerFilter(_filters) {
      if (this.filterCustom) {
        this.$emit("handlerFilter", _filters);
      } else {
        for (let key in _filters) {
          this.filterValue[key] = [];
          if (_filters[key] == null || _filters[key].length == 0) {
            delete this.filterValue[key];
          } else {
            if (_filters[key].length == 1) {
              this.filterValue[key] = _filters[key][0];
            } else {
              this.filterValue[key] = _filters[key];
            }
          }
          this.filterValue[key] = _filters[key].join();
        }
        this.renderTable();
      }
    },
    // 排序
    handlerSort(obj) {
      if (obj.order == null) {
        this.filterValue.sort = "";
      } else {
        this.filterValue.sort = obj.prop + " " + obj.order.slice(0, -6);
      }
      this.renderTable();
      // this.$$emit('sort-change',obj)
    },
    // 页数大小改变
    handleSizeChange(pageSize) {
      this.$set(this.filterValue, "limit", pageSize);
      this.renderTable();
    },
    // 跳页
    handleCurrentChange(page) {
      this.$set(this.filterValue, "page", page);
      this.renderTable();
    },
    // 复选框操作
    handleSelectionChange(selection) {
      this.$emit("selection-change", selection);
    },
    // 重载表格数据
    renderTable() {
      this.loading = true;
      if (!this.page) {
        delete this.filterValue.page;
        delete this.filterValue.limit;
      }
      request({
        url: this.url,
        method: this.method,
        params: Object.assign(this.extendFilterValue, this.filterValue),
      })
        .then((res) => {
          if (res.data.code === 0 && res.data.success) {
            if (this.extendDataKey) {
              this.$set(this, "dataInfo", res.data.data[this.extendDataKey]);
            } else {
              this.$set(this, "dataInfo", res.data.data);
            }
            this.$set(this, "total", res.data.total);
            this.$set(this, "result", res.data);
            this.$emit("change", res.data.data);
            if (this.rowKey) {
              this.dataInfo.forEach((item) => {
                if (item[this.childrenName] > 0) {
                  item[this.hasChildrenName] = true;
                }
              });
            }
          } else {
            this.$message.error(res.data.msg);
          }
          this.loading = false;
        })
        .catch((error) => {
          this.loading = false;
        });
    },
    // 删除行
    deleteRow(index) {
      this.dataInfo.splice(index, 1);
      this.total -= 1;
      if (!this.total) {
        this.total = 0;
      }
    },
    //点击行
    rowClick(row, column, event) {
      this.$emit("row-click", {
        row,
        column,
        event,
      });
    },
    //序号
    indexMethod(index) {
      return (index += 1);
    },
  },
};
</script>

<style lang="scss" scoped>
.el-pagination {
  /* float: right; */
  text-align: center;
  margin-top: 8px;
}
.t-table {
  /deep/.el-table--border td,
  /deep/ .el-table--border th {
    border-right: none;
  }
  /deep/.el-checkbox__inner {
    width: 18px;
    height: 18px;
  }
  /deep/.el-checkbox__inner::after {
    left: 6px;
    top: 4px;
  }
}
</style>
